<template>
  <div id="login-wechat" v-show="isAll">
    <template v-if="!isOnce">
      <div class="qr-code" id="qrCode">
      </div>
      <!-- 不要删 qrCode隐藏不了 -->
      <div class="refresh-qrCode" @click="refreshQrCode">
        刷新二维码<i class="el-icon-refresh"></i>
      </div>
      <div class="oper">
        <span class="text" @click="switchType('account')">账号密码登录 </span>
        |
        <span class="text" @click="switchType('phone')"> 手机号登录</span>
      </div>
    </template>
    <template v-else>
      <el-form :model="form" :rules="rules" ref="wechatForm" class="demo-ruleForm">
        <el-form-item prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input v-model="form.code" type="text" @keyup.enter.native="loginWechat" placeholder="请输入验证码">
            <template #suffix>
              <div class="get-code" @click="ResendCode(form.phone, 'publicApi','getSigninIphone' )">
                发送验证码
              </div>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <!-- <div class="valid">
        <el-button class="valid-btn" @click="loginWechat" type="primary">验证</el-button>
      </div> -->
      <div id="captcha-wechat"></div>
      <div class="login-btn-phone">
        <el-button class="btn" @click="loginPhone()" :loading="loading" type="primary" round>验 证</el-button>
        <!-- <span @click="onSignup" class="blueColor hoverToBlue _span">注册</span> -->
      </div>
    </template>

  </div>
</template>

<script>
import '../plugins/wechatLogin';
import { rules } from '../config/phoneRules';
import useGetCode from '../mixins/useGetCode';


export default {
  name: 'loginWechat',
  props: {
    code: {

    }
  },
  data() {
    return {
      form: {
        phone: '',
        code: '',
        singleVal: ''
      },
      rules: rules,
      loading: false,
      isOnce: false,
      isAll: false,
    };
  },
  mixins: [useGetCode],
  created() {
  },
  mounted() {
    // this.qrCodeIsGenerat();
    this.code && this.loginCode();
    if (!this.code) {
      this.isAll = true;
    }
  },
  methods: {
    refreshQrCode() {
      // this.qrCodeIsGenerat();
    },
    qrCodeIsGenerat() {
      // eslint-disable-next-line no-undef
      var obj = new WxLogin({
        self_redirect: false,
        id: "qrCode",
        appid: "wx8902694a76259bd2",
        scope: "snsapi_login",
        redirect_uri: "http://enterprise.91yikuaiji.com:8756/unitInformation",
        // redirect_uri:'http://localhost:8080/unitInformation',
        state: Math.random() * 10,
        style: "",
        href: `https://unify.yundaizhang.com.cn:8754/wechatLogin.css?random=${Math.random() * 10}`
      });
    },
    loginCode() {
      this.$api.publicApi.LoginWeChat({ code: this.code }).then(res => {
        // code登录成功直接emit  登录失败则切换绑定手机号进行手机号绑定
        const { status, data } = res.data;
        this.isAll = true;
        this.form.singleVal = data.singleVal;

        if (data.statusVal === 40001 && status === 400) { //二维码失效
          this.isOnce = false;
        }
        if (data.statusVal === 40003 && status === 400) { //第一次登录
          this.isOnce = true;
        }
        if (status === 200) { //登录成功
          this.$emit('phoneLoginSuccess', res.data.data);
        }
      });
    },
    loginPhone(nvcVal2) {
      this.$refs.wechatForm.validate(valid => {
        if (valid) {
          this.loading = true;
          // window.nvc.getNVCVal() 第一次无痕验证主动获取的人机信息串
          this.$api.publicApi.LoginMobile({ ...this.form, machineVal: nvcVal2 || window.nvc.getNVCVal() || '' }).then(res => {
            if ((res.data.data.statusVal == '200' || res.data.data.statusVal == '100') && res.data.status == 200) { //无痕验证通过
              // 无痕验证通过执行
              const token = res.data.data.token;
              if (!token) {
                res.data.data.enterpriseList.forEach(item => {
                  item.singleVal = this.form.singleVal;
                });
              }
              // token存在只有一个企业登录成功   token不存在有多个企业进入选择企业
              token ? this.$emit('phoneLoginSuccess', res.data.data) : this.$emit('selectEnterprise', res.data.data.enterpriseList);
            } else if (res.data.data.statusVal == '800' || res.data.data.statusVal == '900') { // 无痕验证失败，直接拦截

            } else if (res.data.data.statusVal == '400') { // 无痕验证失败，触发二次验证
              // 无痕验证失败，触发二次验证
              // 二次验证码（滑动验证码）配置项设置，详情请见滑动验证集成方式文档
              // 二次验证的appkey，scene，test值及success，fail，error的回调由nvc初始化时决定，请不要在二次验证时传入
              var ncoption = {
                //无痕配置 && 滑动验证、刮刮卡、问答验证码通用配置
                // 在二次验证中，请不要配置初始化参数appkey，scene，test的值
                // 声明滑动验证需要渲染的目标ID。
                renderTo: '#captcha-wechat',
                upLang: {
                  'cn': {
                    //加载状态提示。
                    'LOADING': "加载中...",
                    //等待滑动状态提示。
                    'SLIDE': "请向右滑动验证",
                    //验证通过状态提示。
                    'SUCCESS': "验证通过",
                    //验证失败触发拦截状态提示。
                    'ERROR': "非常抱歉，网络出错了...",
                    //验证失败触发拦截状态提示。
                    'FAIL': "验证失败，请重试"
                  }
                }
              };
              // 唤醒二次验证（滑动验证码）
              window.nvc.getNC(ncoption);
              // 滑块高度不够
              var nc_scale = document.querySelector('#nc_1_n1z');
              nc_scale.style = 'height:34px';
            }
            this.loading = false;
          }).catch(err => {
            this.loading = false;
          });
        }
      });
    },
    switchType(e) {
      this.$emit('switchType', e);
    }
  }
};
</script>

<style lang="less" scoped>
#login-wechat {
  #captcha-wechat {
    width: 100%;
    display: flex;
    justify-content: center;
  }
  .qr-code {
    width: 230px;
    height: 1220px;
    margin: 6% auto 0%;
    .img {
      width: 220px;
      height: 220px;
    }
  }
  .refresh-qrCode {
    width: 90px;
    margin: 0 auto;
    font-size: 13px;
    color: #999;
    margin-bottom: 10%;
    cursor: pointer;
    &:hover {
      color: #5b95f9;
    }
  }
  .oper {
    color: #999;
    font-size: 13px;
    cursor: pointer;
    .text:hover {
      color: #5b95f9;
    }
  }
  .el-form-item {
    margin-top: 12%;
  }
  :deep( .el-form-item__content) {
    margin-left: 0 !important;
  }
  .get-code {
    color: #5b95f9;
    cursor: pointer;
  }
  .valid {
    margin-top: 12%;
    .valid-btn {
      width: 200px;
      height: 30px;
      font-size: 13px !important;
      line-height: 12px;
      border-radius: 2px;
      font-weight: 600;
      transition: none;
    }
  }
  .login-btn-phone {
    display: flex;
    flex-direction: column;
    .btn {
      width: 80%;
      margin: 0 auto;
      height: 30px;
      font-size: 13px !important;
      line-height: 12px;
      margin-top: 12%;
      border-radius: 2px;
      font-weight: 600;
      transition: none;
    }
    :deep( ._span ){
      margin-top: 7%;
      font-size: 13px;
      text-decoration: underline;
    }
  }
}
</style>